#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @Time		:2018/1/24 18:17
# @Author	:RNone
import requests
import os
import datetime
import time
from dicttoxml import dicttoxml
from xml.dom.minidom import parseString
import logging
import unittest


class api_base(unittest.TestCase):
	def find_verify(self, text):
		'''找出页面中的verify数据并返回'''
		left = '<input name="__RequestVerificationToken" type="hidden" value="'
		right = '" />'
		return text.split(left)[1].split(right)[0]

	def write_session(self, cookies):
		'''将cookies信息保存到sessionw文件中'''
		cookies_dict = requests.utils.dict_from_cookiejar(cookies)
		text = ''
		with open('vda_login.session', 'w') as f:
			for i in cookies_dict:
				text += '%s=%s&'%(i,cookies_dict[i])
			f.write(text)

	def read_session(self):
		'''
		从session文件中读取cookies信息
		:return: cookies有效返回cookies,无效返回None
		'''
		filePath = ''
		for root,dirs,files in os.walk('./'):
			for file in files:
				if file == 'vda_login.session':
					filePath = root+'/'+file
		if filePath:
			fileCreateTime = os.path.getmtime(filePath)	#获取文件当前时间
			fileCreateTime = self.time_format(fileCreateTime)
			timeNow = datetime.datetime.now().strftime('%Y-%m-%d')
			if str(fileCreateTime) != str(timeNow):
				logging.info('session文件过期，登陆凭证无效')
				return None
			else:
				with open(filePath, 'r') as f:
					text = f.read()
				text = text.split('&')
				cookies = {}
				for i in text:
					if i:
						cookies[i.split('=')[0]]=i.split('=')[1]
				return requests.utils.cookiejar_from_dict(cookies)
		else:
			logging.info('无session文件')
			return None

	def time_format(self,systemTime):
		'''格式化时间'''
		return time.strftime('%Y-%m-%d',time.localtime(systemTime))

	def xml_format(self,data):
		'''字典转化xml数据并返回'''
		data_xml = dicttoxml(data,attr_type=False)
		data_xml = parseString(data_xml)
		data_xml = data_xml.toprettyxml()
		return data_xml

	def write_error(self,data):
		'''写错误日志'''
		with open('./log/error.txt','a+') as f:
			f.write(data)
			f.write('\n')

	def dict_to_tup(self,data):
		'''将post数据转化为元祖发送，requests不支持json数组，通过这种方式避免问题'''
		tupList = []
		for i in data:
			if isinstance(data[i],dict):
				for j in data[i]:
					tupList.append(('%s[%s]'%(i,j),data[i][j]))
			elif isinstance(data[i],list) :
				if not data[i]:
					tupList.append((i,[]))
			else:
				tupList.append((i,data[i]))
		return tuple(tupList)

	def dict_to_list(self, data, upper=None):
		'''字典转化成列表，requests专用'''
		# 定义数据列表，最终将转换为元组
		dataList = []
		# 判断包含上层目录
		if upper:
			for i in data:
				# 如果子元素为字典，则再一次进入函数带参数upper执行一次
				if isinstance(data[i], dict):
					tempData = self.dict_to_list(data[i], '%s[%s]' % (upper, i))
					dataList += tempData
				# 如果子元素为列表，调用list_to_tup函数
				elif isinstance(data[i], list):
					tempData = self.list_to_json_array(data[i], '%s[%s]' % (upper, i))
					dataList += tempData
				# 所有参数键值加上上层标签
				else:
					dataList.append(['%s[%s]' % (upper, i), data[i]])
		# 判断没有上层目录
		else:
			for i in data:
				# 如果子元素为字典，则再一次进入函数带参数upper执行一次
				if isinstance(data[i], dict):
					tempData = self.dict_to_list(data[i], i)
					dataList += tempData
				# 如果子元素为列表，调用list_to_tup函数
				elif isinstance(data[i], list):
					tempData = self.list_to_json_array(data[i], i)
					dataList += tempData
				# 直接将字典转化为元组
				else:
					dataList.append([i, data[i]])
		# 返回值为列表强制转换为元组
		return dataList

	def list_to_json_array(self, data, upper):
		'''列表转换成json数组，配合dict_to_list使用'''
		# 定义数据列表，最终将转换为元组
		dataList = []
		for i in data:
			tempData = self.dict_to_list(i, '%s[%s]' % (upper, data.index(i)))
			if tempData:
				return tempData
		# 返回值为列表强制转换为元组
		return dataList

	def list_to_tup(self, data):
		'''将dict_to_list处理后的列表数据转化为元组，供requests直接使用'''
		tempList = []
		# 通过dict_to_list预处理数据
		data = self.dict_to_list(data)
		# 将数据列表转化为元组
		for i in data:
			tempList.append(tuple(i))
		return tuple(tempList)


if __name__ == '__main__':
	ab = api_base()
	data = {'op': 'add', 'module': 10, '__RequestVerificationToken': 'FkuwgKLedtkQQa5-3VDMOh7N9Y7WFRFQg9gNRIaAoyLfd2WV5_wNWgiizFK_8_jaVB8yuh5KI9QSyBQst0a_3vp6T-wYR2jTvmxJERS4PMI1', 'indexName': 'http-track', 'fields': {'summary': '', 'host': '192.168.40.32', 'imei': '', 'create_time': ''}, 'key_field': 'host'}
	ab.dict_to_tup(data)
